package com.dfdchem.imd.kaiwu.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.dfdchem.imd.kaiwu.R;
import com.dfdchem.imd.kaiwu.activity.base.BaseActivityAnon;
import com.dfdchem.imd.kaiwu.constant.RouterPath;
import com.dfdchem.imd.kaiwu.interfaces.OnHttpResponseListener;
import com.dfdchem.imd.kaiwu.model.Resp;
import com.dfdchem.imd.kaiwu.model.User;
import com.dfdchem.imd.kaiwu.util.CountDownTimerUtils;
import com.dfdchem.imd.kaiwu.util.JSON;
import com.dfdchem.imd.kaiwu.util.RegexUtil;
import com.dfdchem.imd.kaiwu.util.RequestUtil;

import zuo.biao.library.manager.SystemBarTintManager;
import zuo.biao.library.util.Log;

@Route(path = RouterPath.REGISTER_ACTIVITY)
public class RegisterActivity extends BaseActivityAnon implements View.OnClickListener, TextWatcher, OnHttpResponseListener {
    private static final String TAG = "RegisterActivity";

    private Button register_form_get_captcha;
    private Button register_form_submit;
    private EditText register_form_phone;
    private EditText register_form_captcha;
    private EditText register_form_empcard;
    private EditText register_form_password;
    private EditText register_form_password_confirm;

    private static final int request_code_captcha = 1;
    private static final int request_code_register = 2;

    private boolean isRegisterSuccess = false;

    /**
     * 启动这个Activity的Intent
     * @param context
     * @return Intent
     */
    public static Intent createIntent(Context context) {
        Intent intent = new Intent(context, RegisterActivity.class);
        return intent;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        initView();
        initData();
        initEvent();
    }

    @Override
    public void initView() {
        Log.d(TAG, this.getClass().getSimpleName() + " initView");

        register_form_get_captcha = findViewById(R.id.register_form_get_captcha);
        register_form_submit = findViewById(R.id.register_form_submit);

        register_form_phone = findViewById(R.id.register_form_phone);
        register_form_captcha = findViewById(R.id.register_form_captcha);
        register_form_empcard = findViewById(R.id.register_form_empcard);
        register_form_password = findViewById(R.id.register_form_password);
        register_form_password_confirm = findViewById(R.id.register_form_password_confirm);

        SystemBarTintManager tintManager = new SystemBarTintManager(this);
        tintManager.setStatusBarTintEnabled(true);
        tintManager.setStatusBarTintResource(R.color.colorPrimaryDark);
    }

    @Override
    public void initData() {
        Log.d(TAG, this.getClass().getSimpleName() + " initData");
        register_form_get_captcha.setEnabled(false);
    }

    @Override
    public void initEvent() {
        Log.d(TAG, this.getClass().getSimpleName() + " initEvent");
        register_form_phone.addTextChangedListener(this);
        register_form_get_captcha.setOnClickListener(this);
        register_form_submit.setOnClickListener(this);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.forget_password:
                Toast.makeText(this, "请联系管理员", Toast.LENGTH_SHORT).show();
                break;
            case R.id.register_form_get_captcha:
                final String phone = register_form_phone.getEditableText().toString();
                Log.d(TAG, "onClick:" + phone);
                Log.d(TAG, "onClick:" + RegexUtil.isPhone(phone));
                if (phone.length() != 11) {
                    Toast.makeText(this, "手机号长度不正确", Toast.LENGTH_SHORT).show();
                } else if (!RegexUtil.isPhone(phone)) {
                    Toast.makeText(this, "手机号格式不正确，请重新输入", Toast.LENGTH_SHORT).show();
                } else {
                    // TODO 获取手机验证码
                    CountDownTimerUtils mCountDownTimerUtils = new CountDownTimerUtils(this, register_form_get_captcha, 60);
                    mCountDownTimerUtils.start();

                    runThread(TAG + "getCaptcha", new Runnable() {
                        @Override
                        public void run() {
                            RequestUtil.getCaptcha(phone, request_code_captcha, RegisterActivity.this);
                        }
                    });
                }
                break;
            case R.id.register_form_submit:
                if (isRegisterSuccess) {
                    Toast.makeText(this, "您已经注册成功，请返回到登录界面登录", Toast.LENGTH_SHORT).show();
                    return;
                }
                register_form_submit.setEnabled(false);
                final User user = formCheck();
                if (user == null) {
                    register_form_submit.setEnabled(true);
                    return;
                }

                runThread(TAG + "register", new Runnable() {
                    @Override
                    public void run() {
                        RequestUtil.register(user, request_code_register, RegisterActivity.this);
                    }
                });
                break;
            default:
                break;
        }
    }

    private User formCheck(){
        String phone = register_form_phone.getEditableText().toString();
        String code = register_form_captcha.getEditableText().toString();
        String empCardNo = register_form_empcard.getEditableText().toString();
        String password = register_form_password.getEditableText().toString();
        String password_confirm = register_form_password_confirm.getEditableText().toString();

        if (phone.length() != 11) {
            Toast.makeText(this, "手机号长度不正确", Toast.LENGTH_SHORT).show();
            return null;
        } else if (!RegexUtil.isPhone(phone)) {
            Toast.makeText(this, "手机号格式不正确，请重新输入", Toast.LENGTH_SHORT).show();
            return null;
        }
        if (code.length() < 4) {
            Toast.makeText(this, "请输入验证码", Toast.LENGTH_SHORT).show();
            return null;
        }

        if (empCardNo.length() <= 0) {
            Toast.makeText(this, "请输入工号", Toast.LENGTH_SHORT).show();
            return null;
        }

        if (password.length() <= 0 || password_confirm.length() <= 0) {
            Toast.makeText(this, "请输入密码", Toast.LENGTH_SHORT).show();
            return null;
        }

        if (!password.equals(password_confirm)) {
            Toast.makeText(this, "两次输入的密码不一致，请重新输入", Toast.LENGTH_SHORT).show();
            return null;
        }
        User user = new User();
        user.setPhone(phone);
        user.setCode(code);
        user.setEmpCardNo(empCardNo);
        user.setPassword(password);

        return user;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        if (s.length() > 0 && !register_form_get_captcha.isEnabled()) {
            register_form_get_captcha.setEnabled(true);
        } else if (s.length() == 0 && register_form_get_captcha.isEnabled()) {
            register_form_get_captcha.setEnabled(false);
        }
    }

    public void onBackClick(View v) {
        Log.d(TAG, "onBackClick >>>");
        finish();
    }

    @Override
    public void onHttpResponse(int requestCode, String resultJson, Exception e) {
        if (e != null) {
            Toast.makeText(this, "请求失败，" + e.getMessage(), Toast.LENGTH_LONG).show();
            return;
        }
        switch (requestCode) {
            case request_code_register:
                Resp<String> resp = JSON.parseResp(resultJson);
                if (resp == null || resp.getCode() != 200) {
                    Toast.makeText(this, resp != null ? resp.getMsg() : "请求失败，请重试", Toast.LENGTH_SHORT).show();
                } else {
                    isRegisterSuccess = true;
                }

                register_form_submit.setEnabled(true);
                break;

                /*case request_code_captcha:
                    // register_form_get_captcha.setEnabled(true);
                break;*/
            default:break;
        }
    }
}